package logic

import (
	"context"
	"fmt"
	"luck/model/cache"
	"luck/model/mysql"

	"luck/luckrpc/internal/svc"
	"luck/luckrpc/luckrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *luckrpc.CartAddRequest) (*luckrpc.CartAddResponse, error) {
	// todo: add your logic here and delete this line

	var u mysql.User
	var p mysql.Product
	var err error
	if in.Quantity >= 200 {
		return nil, fmt.Errorf("添加单个饮品的数量不能超过200件")
	}

	err = mysql.DB.Debug().Where("id=?", in.UserId).First(&u).Error
	if err != nil {
		return nil, fmt.Errorf("用户不存在")
	}

	err = mysql.DB.Debug().Where("id=?", in.ProductId).First(&p).Error
	if err != nil {
		return nil, fmt.Errorf("饮品不存在,请重新选择饮品")
	}

	if in.Quantity > p.Stock {
		return nil, fmt.Errorf("库存数量不够")
	}

	if cache.IsEx(in.UserId, in.ProductId) {
		err = cache.UpdateCart(in.UserId, in.ProductId, in.Quantity)
		if err != nil {
			return nil, fmt.Errorf("商品数量更新失败")
		}
	} else {
		productMap := map[string]interface{}{
			"productId":  in.ProductId,
			"Name":       p.Name,
			"Price":      p.Price,
			"Stock":      p.Stock,
			"Ingredient": p.Ingredient,
			"Taste":      p.Taste,
			"Status":     p.Status,
			"ImageUrl":   p.ImageUrl,
			"CategoryId": p.CategoryId,
			"quantity":   in.Quantity,
		}
		err = cache.CartAdd(in.UserId, in.ProductId, productMap)
		if err != nil {
			return nil, fmt.Errorf("购物车添加失败")
		}
	}

	return &luckrpc.CartAddResponse{
		Success: true,
		Message: "购物车添加成功",
	}, nil
}
